package com.ruirenyun.util.randcode;

import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author Deng Ye
 */
public class RandCodeUtil {
    private final static String HEAD = "data:image/png;base64,";

    public static String[] generateCodeImg() {
        //第一个参数是验证码 第二个参数是图片
        Object[] objects = RandCodeImageUtil.createImage();
        //将图片转正base64
        BufferedImage image = (BufferedImage) objects[1];
        //转base64
        //io流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            //写入流中
            ImageIO.write(image, "png", baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //转换成字节
        byte[] bytes = baos.toByteArray();
        //转换成base64串
        String base = Base64.encodeBase64String(bytes).trim();
        //删除 \r\n
        base = base.replaceAll("\n", "").replaceAll("\r", "");
        base = HEAD + base;

        return new String[]{(String) objects[0], base};
    }
}
